<template>
  <div class="video-player">
    <div class="video-container" @click="togglePlay">
      <!-- 加载状态显示 -->
      <div v-if="isLoading && !hasError" class="video-overlay loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span></span>
      </div>

      <!-- 错误状态显示 -->
      <div v-if="hasError" class="video-overlay error">
        <el-icon><CircleClose /></el-icon>
        <span>{{ errorMessage }}</span>
        <el-button size="small" type="primary" @click="retryLoad">重试</el-button>
      </div>

      <video
        ref="videoRef"
        class="video-element"
        @timeupdate="onTimeUpdate"
        @loadedmetadata="onLoadedMetadata"
        @ended="onEnded"
        @error="handleVideoError"
        @waiting="isLoading = true"
        @canplay="isLoading = false"
        @progress="updateBufferedProgress"
      >
        <source v-if="videoUrl" :src="videoUrl" type="video/mp4">
        <p>您的浏览器不支持 HTML5 视频播放。</p>
      </video>

      <!-- 播放/暂停按钮覆盖层 -->
      <div v-show="!isPlaying" class="play-overlay">
        <el-icon class="play-icon"><VideoPlay /></el-icon>
      </div>

      <!-- 视频格式选择器 -->
      <div class="format-selector" v-if="formats?.length > 1">
        <el-dropdown @command="handleFormatSelect" trigger="click">
          <el-button type="text" class="control-button">
            <el-icon><VideoCamera /></el-icon>
            {{ formatQualityLabel(currentFormat) }}
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                v-for="format in formats" 
                :key="format.url"
                :command="format"
                :class="{ 'active-format': currentFormat && format.height === currentFormat.height }"
              >
                {{ formatQualityLabel(format) }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 控制栏 -->
      <div class="controls" @click.stop>
        <!-- 进度条 -->
        <div class="progress-bar" @click="onProgressBarClick" @mousemove="handleProgressHover" @mouseleave="hidePreview">
          <div class="buffered-progress" :style="{ width: bufferedProgress + '%' }"></div>
          <div class="progress" :style="{ width: progress + '%' }"></div>
          <!-- 预览缩略图 -->
          <div v-if="showPreview" class="preview-thumbnail" :style="{ left: previewPosition + 'px' }">
            <img v-if="currentThumbnail" :src="currentThumbnail" alt="预览" />
            <span class="preview-time">{{ formatTime(previewTime) }}</span>
          </div>
        </div>

        <div class="control-buttons">
          <!-- 播放/暂停按钮 -->
          <el-button
            class="control-button"
            :icon="isPlaying ? 'Pause' : 'VideoPlay'"
            @click="togglePlay"
            text
          />

          <!-- 音量控制 -->
          <div class="volume-control">
            <el-button
              class="control-button"
              :icon="isMuted ? 'Mute' : 'Microphone'"
              @click="toggleMute"
              text
            />
            <el-slider
              v-model="volume"
              class="volume-slider"
              :min="0"
              :max="100"
              @change="onVolumeChange"
            />
          </div>

          <!-- 时间显示 -->
          <span class="time-display">
            {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
          </span>

          <!-- 播放速度选择器 -->
          <div class="speed-selector">
            <el-dropdown @command="handleSpeedSelect" trigger="click">
              <el-button type="text" class="control-button">
                {{ playbackRate }}x
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="rate in playbackRates" :key="rate" :command="rate">
                    {{ rate }}x
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 全屏按钮 -->
          <el-button
            class="control-button"
            :icon="isFullscreen ? 'FullscreenExit' : 'FullScreen'"
            @click="toggleFullscreen"
            text
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'

let progressIntervalId = null; // 定期保存播放进度的定时器ID
import { VideoPlay, VideoPause, Microphone, Mute, FullScreen, Loading, CircleClose, ArrowDown, VideoCamera } from '@element-plus/icons-vue'

// Props 定义
const props = defineProps({
  videoUrl: {
    type: String,
    required: true
  },
  formats: {
    type: Array,
    default: () => []
  },
  previewThumbnails: Array,
  previewVtt: String
});

// Emits 定义
const emit = defineEmits(['format-change', 'error']);

// 当前选中的格式
const currentFormat = ref(null);

// 处理格式选择
const handleFormatSelect = (format) => {
  currentFormat.value = format;
  emit('format-change', format);
};

// 格式化质量标签
const formatQualityLabel = (format) => {
  if (!format) return '自动';
  
  // 确保format.height是数字
  const height = parseInt(format.height || 0);
  
  let label = '';
  if (height >= 1080) {
    label = 'Full HD';
  } else if (height >= 720) {
    label = 'HD';
  } else if (height >= 480) {
    label = 'SD';
  } else if (height > 0) {
    label = 'LD';
  } else {
    return '自动';
  }
  
  return `${label} (${height}p)`;
};

// 视频相关的响应式变量
const videoRef = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const progress = ref(0)
const volume = ref(100)
const isMuted = ref(false)
const isFullscreen = ref(false)
const isLoading = ref(true)
const hasError = ref(false)
const errorMessage = ref('')
const playbackRate = ref(1.0);
const playbackRates = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];
const bufferedProgress = ref(0);

// 预览相关变量
const showPreview = ref(false)
const previewPosition = ref(0)
const previewTime = ref(0)
const currentThumbnail = ref('')

// 处理进度条悬停
const handleProgressHover = (event) => {
  const progressBar = event.currentTarget
  const rect = progressBar.getBoundingClientRect()
  const offsetX = event.clientX - rect.left
  
  // 计算预览位置和时间
  previewPosition.value = offsetX
  previewTime.value = (offsetX / progressBar.offsetWidth) * duration.value
  
  // 根据时间获取对应的缩略图
  if (props.previewThumbnails?.length) {
    const thumbnailIndex = Math.floor(previewTime.value / (duration.value / props.previewThumbnails.length))
    currentThumbnail.value = props.previewThumbnails[thumbnailIndex]
  }
  
  showPreview.value = true
}

// 隐藏预览
const hidePreview = () => {
  showPreview.value = false
}

// 检查视频源是否有效
const checkVideoSource = async (url) => {
  try {
    console.log('检查视频源:', url);
    const response = await fetch(url, { 
      method: 'HEAD',
      headers: {
        'Accept': 'video/mp4,video/*;q=0.9,*/*;q=0.8'
      }
    });
    
    console.log('视频源检查状态:', response.status, response.statusText);
    const contentType = response.headers.get('content-type');
    console.log('视频源Content-Type:', contentType);
    
    if (!response.ok) {
      throw new Error(`视频源无法访问: ${response.status} ${response.statusText}`);
    }
    
    if (!contentType || !contentType.includes('video/')) {
      throw new Error(`不支持的视频格式: ${contentType}`);
    }
    
    return true;
  } catch (error) {
    console.error('视频源检查失败:', error);
    errorMessage.value = error.message;
    hasError.value = true;
    return false;
  }
};

// 添加重试加载方法
const retryLoad = async () => {
  console.log('尝试重新加载视频...');
  if (!props.videoUrl) {
    console.error('无法重试：视频URL未提供');
    return;
  }
  
  isLoading.value = true;
  hasError.value = false;
  errorMessage.value = '';
  
  const isValid = await checkVideoSource(props.videoUrl);
  if (!isValid) {
    emit('error', '视频源检查失败，无法加载视频');
    return;
  }
  
  // 重置视频元素
  if (videoRef.value) {
    videoRef.value.load();
  }
};

// 添加网络状态监听
onMounted(() => {
  window.addEventListener('online', () => {
    if (hasError.value) {
      retryLoad()
    }
  })
  window.addEventListener('offline', () => {
    errorMessage.value = '网络连接已断开，请检查网络设置'
    hasError.value = true
    isLoading.value = false
    emit('error', errorMessage.value);
  })
})

onUnmounted(() => {
  window.removeEventListener('online', retryLoad)
  window.removeEventListener('offline', () => {})
})

// 视频元数据加载完成
const onLoadedMetadata = () => {
  if (!videoRef.value) return;
  console.log('视频元数据加载完成');
  console.log('视频时长:', videoRef.value.duration);
  console.log('视频尺寸:', videoRef.value.videoWidth, 'x', videoRef.value.videoHeight);
  
  duration.value = videoRef.value.duration;
  isLoading.value = false;
  hasError.value = false;
  errorMessage.value = '';
  // 设置初始播放速度
  videoRef.value.playbackRate = playbackRate.value;
};

// 播放控制
const togglePlay = async () => {
  if (!videoRef.value) return;
  
  try {
    if (videoRef.value.paused) {
      // 播放前检查视频源
      const isValid = await checkVideoSource(props.videoUrl);
      if (!isValid) {
        return;
      }
      
      console.log('尝试播放视频...');
      await videoRef.value.play();
      isPlaying.value = true;
    } else {
      console.log('暂停视频播放');
      videoRef.value.pause();
      isPlaying.value = false;
    }
  } catch (error) {
    console.error('播放控制错误:', error);
    if (error.name === 'AbortError') {
      console.log('播放被中断，可能是用户手动暂停');
      return;
    }
    
    emit('error', '视频播放失败: ' + error.message);
    hasError.value = true;
    isPlaying.value = false;
  }
};

// 时间更新处理
const onTimeUpdate = () => {
  if (!videoRef.value) return

  currentTime.value = videoRef.value.currentTime
  progress.value = (currentTime.value / duration.value) * 100
}

// 视频播放结束
const onEnded = () => {
  isPlaying.value = false
  currentTime.value = 0
  progress.value = 0
}

// 进度条点击处理
const onProgressBarClick = (event) => {
  if (!videoRef.value) return

  const progressBar = event.currentTarget
  const clickPosition = event.offsetX
  const progressBarWidth = progressBar.offsetWidth
  const seekTime = (clickPosition / progressBarWidth) * duration.value

  videoRef.value.currentTime = seekTime
}

// 音量控制
const onVolumeChange = (value) => {
  if (!videoRef.value) return
  videoRef.value.volume = value / 100
  isMuted.value = value === 0
}

// 静音切换
const toggleMute = () => {
  if (!videoRef.value) return

  if (isMuted.value) {
    videoRef.value.volume = volume.value / 100
    isMuted.value = false
  } else {
    videoRef.value.volume = 0
    isMuted.value = true
  }
}

// 全屏控制
const toggleFullscreen = async () => {
  try {
    if (!document.fullscreenElement) {
      await videoRef.value.requestFullscreen()
      isFullscreen.value = true
    } else {
      await document.exitFullscreen()
      isFullscreen.value = false
    }
  } catch (error) {
    emit('error', '全屏模式切换失败');
    console.error('全屏切换错误:', error)
  }
}

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds) return '00:00'

  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

// 处理键盘事件
const handleKeydown = (event) => {
  // 避免在输入框等元素中触发
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
    return;
  }

  switch (event.code) {
    case 'Space':
      event.preventDefault();
      togglePlay();
      break;
    case 'ArrowLeft':
      event.preventDefault();
      // 快退5秒
      if (videoRef.value) {
        videoRef.value.currentTime = Math.max(0, videoRef.value.currentTime - 5);
      }
      break;
    case 'ArrowRight':
      event.preventDefault();
      // 快进5秒
      if (videoRef.value) {
        videoRef.value.currentTime = Math.min(duration.value, videoRef.value.currentTime + 5);
      }
      break;
    case 'ArrowUp':
      event.preventDefault();
      // 增加音量
      volume.value = Math.min(100, volume.value + 5);
      if (videoRef.value) {
        videoRef.value.volume = volume.value / 100;
        isMuted.value = volume.value === 0;
      }
      break;
    case 'ArrowDown':
      event.preventDefault();
      // 降低音量
      volume.value = Math.max(0, volume.value - 5);
      if (videoRef.value) {
        videoRef.value.volume = volume.value / 100;
        isMuted.value = volume.value === 0;
      }
      break;
    case 'KeyM':
      event.preventDefault();
      // 静音切换
      toggleMute();
      break;
    case 'KeyF':
      event.preventDefault();
      // 全屏切换
      toggleFullscreen();
      break;
  }
};

// 播放速度选择
const handleSpeedSelect = (rate) => {
  if (!videoRef.value) return;
  
  console.log('设置播放速度:', rate);
  playbackRate.value = rate;
  videoRef.value.playbackRate = rate;
};

// 组件挂载时添加事件监听
onMounted(() => {
  console.log('视频播放器组件已挂载');
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('keydown', handleKeydown);
  
  // 设置默认格式
  if (props.formats?.length > 0) {
    currentFormat.value = props.formats[0];
  }
  
  if (videoRef.value) {
    console.log('初始化视频元素事件监听');
    videoRef.value.addEventListener('progress', handleProgress);
    preloadVideo();
  }
  
  // 网络状态监听
  window.addEventListener('online', () => {
    console.log('网络已连接，尝试重新加载视频');
    if (hasError.value) {
      retryLoad();
    }
  });
  
  window.addEventListener('offline', () => {
    console.log('网络已断开');
    errorMessage.value = '网络连接已断开，请检查网络设置';
    hasError.value = true;
    isLoading.value = false;
    emit('error', errorMessage.value);
  });

  // 启动定期保存播放进度的定时器
  if (!progressIntervalId) { // 仅在尚未启动时启动定时器
    progressIntervalId = setInterval(() => {
      // saveVideoProgress 函数内部会检查 videoRef.value, isLoggedIn.value 和 videoId.value
      saveVideoProgress();
    }, 30000);
  }
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('keydown', handleKeydown);
  if (videoRef.value) {
    videoRef.value.removeEventListener('progress', handleProgress);
  }
  // 移除网络状态监听
  window.removeEventListener('online', retryLoad);
  window.removeEventListener('offline', () => {});
});

// 监听视频加载进度
const handleProgress = () => {
  if (!videoRef.value) return
  
  const buffered = videoRef.value.buffered
  if (buffered.length > 0) {
    const bufferedEnd = buffered.end(buffered.length - 1)
    const duration = videoRef.value.duration
    const loadProgress = (bufferedEnd / duration) * 100
    console.log('视频加载进度:', loadProgress + '%')
  }
}

// 视频预加载
const preloadVideo = async () => {
  if (!props.videoUrl) {
    console.error('视频URL未提供');
    errorMessage.value = '视频URL未提供';
    hasError.value = true;
    return;
  }
  
  console.log('开始加载视频:', props.videoUrl);
  try {
    isLoading.value = true;
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 30000);
    
    const response = await fetch(props.videoUrl, {
      signal: controller.signal,
      headers: {
        'Accept': 'video/mp4,video/*;q=0.9,*/*;q=0.8'
      }
    });
    
    clearTimeout(timeoutId);
    console.log('视频请求状态:', response.status, response.statusText);
    console.log('Content-Type:', response.headers.get('content-type'));
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const contentType = response.headers.get('content-type');
    console.log('视频文件类型:', contentType);
    
    if (!contentType || !contentType.includes('video/')) {
      throw new Error('无效的视频类型: ' + contentType);
    }
    
    const contentLength = response.headers.get('content-length');
    if (contentLength) {
      const sizeInMB = parseInt(contentLength) / (1024 * 1024);
      console.log('视频文件大小:', sizeInMB.toFixed(2) + 'MB');
    }
    
    isLoading.value = false;
    
  } catch (error) {
    console.error('视频预加载失败:', error);
    hasError.value = true;
    isLoading.value = false;
    
    if (error.name === 'AbortError') {
      errorMessage.value = '视频加载超时，请检查网络连接';
    } else if (error.message.includes('HTTP error')) {
      errorMessage.value = `视频加载失败 (${error.message})`;
    } else {
      errorMessage.value = '视频加载失败: ' + error.message;
    }
    
    emit('error', errorMessage.value);
  }
};

// 视频错误处理
const handleVideoError = async (event) => {
  console.error('视频加载错误:', event);
  hasError.value = true;
  isLoading.value = false;
  isPlaying.value = false;

  // 检查网络连接状态
  if (!navigator.onLine) {
    errorMessage.value = '网络连接已断开，请检查网络设置';
    return;
  }

  const error = event.target.error;
  console.log('错误代码:', error.code);
  
  switch (error.code) {
    case error.MEDIA_ERR_ABORTED:
      errorMessage.value = '视频加载已取消';
      break;
    case error.MEDIA_ERR_NETWORK:
      errorMessage.value = '网络错误导致视频加载失败';
      // 网络错误时检查视频源
      const isValid = await checkVideoSource(props.videoUrl);
      if (!isValid) {
        return;
      }
      break;
    case error.MEDIA_ERR_DECODE:
      errorMessage.value = '视频解码失败，可能是格式不支持';
      break;
    case error.MEDIA_ERR_SRC_NOT_SUPPORTED:
      errorMessage.value = '不支持的视频格式或视频源无法访问';
      break;
    default:
      errorMessage.value = '视频加载失败，请稍后重试';
  }

  emit('error', errorMessage.value);
};

// 监听 videoUrl 变化，重新加载视频并重置状态
watch(() => props.videoUrl, (newUrl, oldUrl) => {
  if (!newUrl) {
    console.warn('视频URL为空');
    hasError.value = true;
    errorMessage.value = '视频链接无效';
    return;
  }
  
  // 只有在URL真正变化时才重置视频
  if (newUrl !== oldUrl) {
    console.log(`视频URL发生变化: ${oldUrl || '无'} -> ${newUrl}`);
    
    // 重置状态
    isPlaying.value = false;
    currentTime.value = 0;
    duration.value = 0;
    progress.value = 0;
    isLoading.value = true;
    hasError.value = false;
    errorMessage.value = '';

    // 延迟执行视频重置，确保在Vue状态更新后执行
    setTimeout(() => {
      if (videoRef.value) {
        try {
          // 重置视频元素
          videoRef.value.pause();
          videoRef.value.currentTime = 0;
          
          // 尝试刷新视频源
          const sourceElement = videoRef.value.querySelector('source');
          if (sourceElement) {
            sourceElement.src = newUrl;
          }
          
          // 强制浏览器重新加载视频
          videoRef.value.load();
          console.log('视频元素已重新加载');
          
          // 预加载视频
          preloadVideo();
        } catch (err) {
          console.error('重置视频时出错:', err);
          hasError.value = true;
          errorMessage.value = '加载视频时出错: ' + err.message;
        }
      } else {
        console.warn('视频元素不存在，无法重新加载');
      }
    }, 10); // 短暂延迟确保DOM已更新
  } else {
    console.log('视频URL未变化，忽略更新');
  }
}, { immediate: true });

// 记忆播放位置相关变量
const videoId = ref('');
const STORAGE_KEY_PREFIX = 'video_progress_';

// 保存播放进度
const saveVideoProgress = () => {
  if (!videoRef.value || !videoId.value) return;
  
  // 只有当视频播放超过5秒时才保存进度
  if (videoRef.value.currentTime > 5) {
    const progressData = {
      currentTime: videoRef.value.currentTime,
      duration: videoRef.value.duration,
      timestamp: Date.now()
    };
    localStorage.setItem(STORAGE_KEY_PREFIX + videoId.value, JSON.stringify(progressData));
  }
};

// 加载播放进度
const loadVideoProgress = () => {
  if (!videoRef.value || !videoId.value) return;
  
  const savedProgress = localStorage.getItem(STORAGE_KEY_PREFIX + videoId.value);
  if (savedProgress) {
    try {
      const progressData = JSON.parse(savedProgress);
      // 检查保存的进度是否在7天内，且播放进度小于视频总时长的95%
      const isRecent = (Date.now() - progressData.timestamp) < 7 * 24 * 60 * 60 * 1000;
      const isNotNearEnd = progressData.currentTime < (progressData.duration * 0.95);
      
      if (isRecent && isNotNearEnd && progressData.currentTime > 5) {
        videoRef.value.currentTime = progressData.currentTime;
        // 显示提示
        showToast(`已从上次观看的位置继续播放`);
      }
    } catch (e) {
      console.error('加载播放进度失败:', e);
    }
  }
};

// 显示提示信息
const toastMessage = ref('');
const isToastVisible = ref(false);
const showToast = (message) => {
  toastMessage.value = message;
  isToastVisible.value = true;
  setTimeout(() => {
    isToastVisible.value = false;
  }, 3000);
};

// 设置视频ID
const setVideoId = (id) => {
  videoId.value = id;
};

// 暴露给父组件的方法
defineExpose({
  setVideoId
});

// 组件卸载时清理
onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('keydown', handleKeydown);

  // 清理定期保存播放进度的定时器
  if (progressIntervalId) {
    clearInterval(progressIntervalId);
    progressIntervalId = null;
  }

  if (videoRef.value) {
    videoRef.value.removeEventListener('progress', handleProgress);

    // 保存最终播放进度 (saveVideoProgress 函数内部会进行必要的检查)
    saveVideoProgress();
  }
});

// 添加一个显式的清理方法
const cleanup = () => {
  if (videoRef.value) {
    videoRef.value.pause();
    videoRef.value.src = '';
    videoRef.value.load(); // 尝试加载空源以释放资源
  }

};

</script>

<style scoped>
.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  gap: 10px;
  z-index: 2;
}

.video-overlay.loading {
  cursor: wait;
}

.video-overlay.error {
  cursor: default;
}

.video-overlay .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.video-overlay span {
  font-size: 16px;
  text-align: center;
  max-width: 80%;
  margin-bottom: 15px;
}

.video-player {
  width: 100%;
  max-width: 1280px;
  margin: 0 auto;
  position: relative;
  background: #000;
  overflow: hidden;
  aspect-ratio: 16/9;
}

.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: pointer;
  overflow: hidden;
  background-color: #000 !important; 
  z-index: 1;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
  background-color: #000; 
}

.play-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  padding: 20px;
  cursor: pointer;
}

.play-icon {
  font-size: 32px;
  color: white;
}

.controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));
  padding: 10px;
  transition: opacity 0.3s;
  z-index: 1;
}

.control-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
  z-index: 2;
}

.control-button {
  color: white;
  font-size: 20px;
  padding: 4px;
}

.control-button:hover {
  background: none;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 5px;
  width: 120px;
}

uaua.volume-slider {
  width: 60px;
}

@media (max-width: 768px) {
  .volume-control {
    width: 100px;
  }
  .volume-slider {
    width: 50px;
  }
}

.time-display {
  color: white;
  font-size: 14px;
  margin-left: auto;
  margin-right: 10px;
}

.format-selector {
  display: inline-flex;
  align-items: center;
  margin-left: 10px;
  margin-right: 10px;
}

.format-selector :deep(.el-button) {
  color: #fff;
  font-size: 14px;
  padding: 0;
  min-height: unset;
  display: flex;
  align-items: center;
  gap: 4px;
}

.format-selector :deep(.el-dropdown-menu) {
  background: rgba(0, 0, 0, 0.9);
  border: none;
  padding: 4px 0;
}

.format-selector :deep(.el-dropdown-menu__item) {
  color: #fff;
  font-size: 14px;
  padding: 8px 16px;
  line-height: 1.4;
}

.format-selector :deep(.el-dropdown-menu__item:hover) {
  background-color: rgba(255, 255, 255, 0.1);
}

.active-format {
  color: var(--el-color-primary) !important;
  font-weight: bold;
}

.speed-selector {
  margin-left: 10px;
}

.speed-selector :deep(.el-button) {
  color: #fff;
  font-size: 14px;
  padding: 0;
  min-height: unset;
}

.speed-selector :deep(.el-dropdown-menu) {
  background: rgba(0, 0, 0, 0.9);
  border: none;
  padding: 4px 0;
}

.speed-selector :deep(.el-dropdown-menu__item) {
  color: #fff;
  font-size: 14px;
  padding: 8px 16px;
  line-height: 1.4;
}

.speed-selector :deep(.el-dropdown-menu__item:hover) {
  background-color: rgba(255, 255, 255, 0.1);
}

.progress-bar {
  width: 100%;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  cursor: pointer;
  margin-bottom: 10px;
  border-radius: 2px;
  position: relative;
}

.progress {
  height: 100%;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.preview-thumbnail {
  position: absolute;
  bottom: 40px;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  padding: 4px;
  border-radius: 4px;
  pointer-events: none;
  z-index: 3;
}

.preview-thumbnail img {
  width: 160px;
  height: 90px;
  object-fit: cover;
  display: block;
}

.preview-time {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  color: white;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.8);
  padding: 2px 4px;
  border-radius: 2px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .volume-slider {
    width: 60px;
  }

  .control-button {
    font-size: 18px;
  }

  .time-display {
    font-size: 12px;
  }
}
</style>

/* 缓冲进度条样式 */
.buffered-progress {
  position: absolute;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.3);
  transition: width 0.2s;
}


const updateBufferedProgress = () => {
  if (!videoRef.value) return;
  
  const video = videoRef.value;
  if (video.buffered.length > 0 && video.duration > 0) {
    const bufferedEnd = video.buffered.end(video.buffered.length - 1);
    bufferedProgress.value = (bufferedEnd / video.duration) * 100;
  }
};